package com.zookeeper;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.util.concurrent.CountDownLatch;

/**
 * @Author : hebad90@163.com
 * @Date : 2014/10/26 11:59
 * @From : javalearn
 */
public class Test {
    public static void main(String[] args) throws Exception {
        final CountDownLatch connectedLatch = new CountDownLatch(1);
        final ZooKeeper zk = new ZooKeeper("localhost:2181", 50000, null);
        regist(zk);

        zk.delete("/java",4);
        CountDownLatch latch = new CountDownLatch(1);
        latch.await();

    }
    static void regist(ZooKeeper zk){
        try {
            zk.exists("/java",new MyWatch(zk));
            zk.getChildren("/java",new MyWatch1(zk));
            zk.getData("/java", new MyWatch2(zk), null);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    static class MyWatch implements Watcher{
        ZooKeeper zk;
        public MyWatch(ZooKeeper zk){
            this.zk=zk;
        }
        public void process(WatchedEvent watchedEvent) {
            System.out.println("exist:"+watchedEvent+"\n---");
            try {
                zk.exists("/java", new MyWatch(zk));
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class MyWatch1 implements Watcher{
        ZooKeeper zk;
        public MyWatch1(ZooKeeper zk){
            this.zk=zk;
        }
        public void process(WatchedEvent watchedEvent) {
            System.out.println("getChild:"+watchedEvent+"\n---");
            try {
                zk.getChildren("/java", new MyWatch1(zk));
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class MyWatch2 implements Watcher{
        ZooKeeper zk;
        public MyWatch2(ZooKeeper zk){
            this.zk=zk;
        }
        public void process(WatchedEvent watchedEvent) {
            System.out.println("getData:"+watchedEvent+"\n---");
            try {
                zk.getData("/java", new MyWatch2(zk), null);
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
